<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter=24>
<!--				<a-col :span="6">-->
<!--					<a-form-item label="" name="projectName">-->
<!--						<CompanySelect itemType="project" colSpan=24 @change-company-select-event="changeCompanySelectEvent"  />-->
<!--					</a-form-item>-->
<!--				</a-col>-->
				<a-col :span="6">
					<a-form-item label="资产类别" name="commodityName">
						<a-select v-model:value="searchFormState.commodityCode" @change="changeCommodityName" allow-clear>
							<a-select-option
								v-for="option in commodityList"
								:key="option.code"
								:value="option.code"
								:label="option.name"
							>
								{{ option.name }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="办公用品类型" name="officeSupplie">
						<a-select
							v-model:value="searchFormState.officeSupplies"
							placeholder="请选择案件状态"
							:options="OfficeSupplies"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="月份" name="month">
						<a-range-picker v-model:value="searchFormState.month" picker="month" format="YYYY-MM" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="所属公司">
						<a-tree-select
							v-model:value="searchFormState.dept"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择组织"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:tree-default-expanded-keys="treeDefaultExpandedKeys"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="支付类型" name="type">
						<a-select v-model:value="searchFormState.type" placeholder="请选择类型" :options="typeList" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="table.refresh(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('amsPurchaseOrderAdd')">
						<template #icon>
							<plus-outlined />
						</template>
						新增
					</a-button>
					<xn-batch-button
						v-if="hasPerm('amsPurchaseOrderBatchDelete')"
						buttonName="批量删除"
						icon="DeleteOutlined"
						:selectedRowKeys="selectedRowKeys"
						@batchCallBack="deleteBatchAmsPurchaseOrder"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('amsPurchaseOrderEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['amsPurchaseOrderEdit', 'amsPurchaseOrderDelete'], 'and')" />
						<a-popconfirm title="确定要删除吗？" @confirm="deleteAmsPurchaseOrder(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('amsPurchaseOrderDelete')">删除 </a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<a-card :bordered="false">
		<a-form>
			<a-col>
				<a-form-item label="总金额">{{ totalMoney}}</a-form-item>
			</a-col>
		</a-form>
	</a-card>
	<Form ref="formRef" @successful="table.refresh(true)" />
</template>

<script setup name="purchaseorder">
	import Form from './form.vue'
	import amsPurchaseOrderApi from '@/api/ams/purchase/amsPurchaseOrderApi'
	import dayjs from 'dayjs'
	import amsCommodityInfoApi from '@/api/ams/commodity/amsCommodityInfoApi'
	import bizUserApi from '@/api/biz/bizUserApi'
	import tool from '@/utils/tool'

	const OfficeSupplies = tool.dictList('Office_supplies')

	const searchFormState = reactive({
		projectName: '',
		month: '',
		secondDirect: '',
		dept: '',
		type: 1,
		projectCode: '',
		officeSupplies: '',
		commodityCode: ''
	})
	const searchFormRef = ref()
	const table = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const columns = [
		{
			title: '资产类别',
			dataIndex: 'commodityName'
		},
		{
			title: '二级菜单',
			dataIndex: 'officeSuppliesName'
		},
		{
			title: '供应商名称',
			dataIndex: 'supplierName'
		},
		{
			//就是预算和采购
			title: '采购类型',
			dataIndex: 'type',
			customRender: ({ text }) => getpurchaseTypeLabel(text)
		},
		{
			title: '计费类型',
			dataIndex: 'billingType',
			customRender: ({ text }) => getBillingTypeLabel(text)
		},
		{
			title: '采购数量',
			dataIndex: 'purchaseQuantity'
		},
		{
			title: '采购单价',
			dataIndex: 'unitPrice'
		},
		{
			title: '采购总价',
			dataIndex: 'totalPrice'
		},
		{
			title: '成本部门',
			dataIndex: 'neededDepartmentName'
		},
		{
			title: '使用地址',
			dataIndex: 'address'
		},
		{
			title: '预算/采购月份',
			dataIndex: 'month'
		},
		{
			title: '所属项目',
			dataIndex: 'projectName'
		}
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['amsPurchaseOrderEdit', 'amsPurchaseOrderDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: '150px'
		})
	}
	const typeList = ref([
		{
			value: 1,
			label: '实付'
		},
		{
			value: 2,
			label: '预算'
		}
	])
	const selectedRowKeys = ref([])
	const treeData = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	searchFormState.month = [dayjs().endOf('month'), dayjs().endOf('month')]
	const totalMoney = ref(0)
	const loadData = (parameter) => {
		const searchFormParam = JSON.parse(JSON.stringify(searchFormState))
		if (searchFormParam.month) {
			searchFormParam.start = searchFormParam.month[0]
			searchFormParam.end = searchFormParam.month[1]
			delete searchFormParam.month
		}
		amsPurchaseOrderApi.amsPurchaseOrderGetMoney(Object.assign(parameter, searchFormParam)).then((data) => {
			console.log(data)
			totalMoney.value = data
		})
		return amsPurchaseOrderApi.amsPurchaseOrderPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		table.value.refresh(true)
	}
	// 删除
	const deleteAmsPurchaseOrder = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		amsPurchaseOrderApi.amsPurchaseOrderDelete(params).then(() => {
			table.value.refresh(true)
		})
	}
	const changeCompanySelectEvent = (val) => {
		searchFormState.projectCode = val.projectCode
		console.log(searchFormState.projectCode)
	}
	// 批量删除
	const deleteBatchAmsPurchaseOrder = (params) => {
		amsPurchaseOrderApi.amsPurchaseOrderDelete(params).then(() => {
			table.value.clearRefreshSelected()
		})
	}
	const treeDefaultExpandedKeys = ref([])

	const changeCommodityName = (val) => {
		console.log(val)
		searchFormState.commodityName = val
		console.log(searchFormState.commodityName)
	}

	const getpurchaseTypeLabel = (value) => {
		const type = typeList.value.find((item) => item.value === value)
		return type ? type.label : '未知'
	}
	// 创建映射函数
	const getBillingTypeLabel = (value) => {
		const type = billingTypeList.value.find((item) => item.value === value)
		return type ? type.label : '未知'
	}
	const billingTypeList = ref([
		{
			value: 1,
			label: '包月'
		},
		{
			value: 2,
			label: '计件'
		}
	])
	// 格式化选项列表
	const commodityList = ref([])
	onMounted(() => {
		// 获取项目列表
		amsCommodityInfoApi.amsCommodityList().then((res) => {
			commodityList.value = res
		})
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				treeData.value = res
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								treeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		})
	})
</script>
